package cn.edu.qfnu.oj.web.controller;


import cn.edu.qfnu.oj.entity.Student;
import cn.edu.qfnu.oj.entity.Teacher;
import cn.edu.qfnu.oj.service.StudentService;
import cn.edu.qfnu.oj.service.TeacherService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "admin/")
public class AdminController {

    private static final Logger log = LoggerFactory.getLogger(AdminController.class);

    private StudentService studentService;
    private TeacherService teacherService;

    @Autowired
    public AdminController(StudentService studentService, TeacherService teacherService) {
        this.studentService = studentService;
        this.teacherService = teacherService;
    }

    @RequestMapping(value = "add", method = RequestMethod.POST)
    public Map<String, String> add(String type, String id, String password, String email) {
        Map<String, String> jsonMap = new HashMap<>();

        try {
            switch (type) {
                case "学生":
                    Student student = new Student(id, password, email);
                    studentService.saveOrUpdate(student);
                    jsonMap.put("result", "success");
                    log.info("添加了一个学生用户");
                    break;
                case "老师":
                    Teacher teacher = new Teacher(id, password, email);
                    teacherService.saveOrUpdate(teacher);
                    jsonMap.put("result", "success");
                    log.info("添加了一个教师用户");
                    break;
                default:
                    log.warn("错误的用户类型");
                    jsonMap.put("result", "Wrong Type");
                    break;
            }
        } catch (Exception e) {
            log.error("添加新用户时出现错误", e);
            jsonMap.put("result", "error");
        }
        return jsonMap;
    }
}
